// pages/user/address/address.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        addresses: [],
        cloud: null,
        bookId: ''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.initSharedCloud();
        if (options.bookId) {
            this.setData({ bookId: options.bookId });
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    async initSharedCloud() {
        const cloud = new wx.cloud.Cloud({
            resourceAppid: 'wx3199c80279c7b8c3',
            resourceEnv: 'education-6gwexwp8488514df'
        });
        
        try {
            await cloud.init();
            this.setData({ cloud });
            this.loadAddresses();
        } catch (err) {
            console.error('初始化云环境失败：', err);
        }
    },

    async loadAddresses() {
        try {
            const { cloud } = this.data;
            const db = cloud.database();
            const userInfo = getApp().globalData.userInfo;
            
            const { data } = await db.collection('addresses')
                .where({
                    userId: userInfo._id
                })
                .get();
            
            this.setData({ addresses: data });
        } catch (err) {
            console.error('加载地址失败：', err);
        }
    },

    goToAddAddress() {
        const { bookId } = this.data;
        wx.navigateTo({
            url: `/pages/user/address/edit/edit${bookId ? '?bookId=' + bookId : ''}`
        });
    },

    editAddress(e) {
        const addressId = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: `/pages/user/address/edit/edit?id=${addressId}`
        });
    },

    deleteAddress(e) {
        const addressId = e.currentTarget.dataset.id;
        wx.showModal({
            title: '提示',
            content: '确定要删除这个地址吗？',
            success: async (res) => {
                if (res.confirm) {
                    try {
                        const { cloud } = this.data;
                        const db = cloud.database();
                        await db.collection('addresses').doc(addressId).remove();
                        this.loadAddresses();
                        wx.showToast({
                            title: '删除成功',
                            icon: 'success'
                        });
                    } catch (err) {
                        console.error('删除地址失败：', err);
                        wx.showToast({
                            title: '删除失败',
                            icon: 'error'
                        });
                    }
                }
            }
        });
    }
})